package com.changanw.dd.datasource;

import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
public class DynamicDatasource extends AbstractRoutingDataSource {

    public DynamicDatasource(LoadDataSource loadDataSource) {
        final Map<String, DataSourceProxy> dataSourceMap = loadDataSource.loadAllDatasource();
        //1、设置所有的数据源
        super.setTargetDataSources(new HashMap<>(dataSourceMap));
        //2、设置默认数据源
        super.setDefaultTargetDataSource(dataSourceMap.get(DataSourcetype.DEFAULT_DS_NAME));
        //3
        super.afterPropertiesSet();
    }

    /**
     * 返回数据源名称，系统需要获取数据源时，会调用这个方法，获取数据源名称
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {

        return DynamicDataSourceContextHolder.getDataSource();
    }
}
